package com.example.saifly.login;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.Activity;
import com.example.common.Application.MyApplication;
import com.example.common.Retrofit.RetrofitHelper;
import com.example.common.Util.RegxUtil;
import com.example.saifly.R;
import com.example.saifly.mainPage.MainPageActivity;

import java.io.IOException;
import java.util.Date;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;

public class IndexActivity extends Activity {

    private LinearLayout llShowMore;
    private int isPatient=1;
    private String identify="default";
    private RelativeLayout rlPatient,rlRelative;
    private TextView tvContactTip;
    private EditText etContactPhone,etVerifyCode;
    private Button btStart,btReget;
    private String uid;
    private ConstraintLayout clVerify;
    private boolean getVerifyAlready=false;
    private TimeCount timeCount;

    private SharedPreferences sharedPreferences;
//   private TextView tvSkip;  跳过按钮
//    private KProgressHUD hud=KProgressHUD.create(IndexActivity.this)
//            .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
//            .setLabel("Please wait")
//            .setAnimationSpeed(2)
//            .setDimAmount(0.5f);

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_index;
    }

    @Override
    protected void init() {
        super.init();
        Intent intent=getIntent();
        uid=intent.getStringExtra("uid");

        rlPatient=findViewById(R.id.index_identity_patient);
        rlRelative=findViewById(R.id.index_identity_relative);
        llShowMore=findViewById(R.id.index_layout_set_relation);
        tvContactTip=findViewById(R.id.index_contact_tip);
        etContactPhone=findViewById(R.id.index_contact_phone);
        btStart=findViewById(R.id.index_start);
        btReget=findViewById(R.id.index_reget_verify_code);
        etVerifyCode=findViewById(R.id.index_verify_code);
        clVerify=findViewById(R.id.index_layout_verify);
        timeCount = new TimeCount(60000,1000,btReget);
//        tvSkip=findViewById(R.id.index_skip);

        //初始化全局变量，稍后用于存入uid
        sharedPreferences= MyApplication.getContext().getSharedPreferences("config", Context.MODE_PRIVATE);

        //初始化选择身份的功能
        initChooseIdentity();

        //初始化下方按钮进行下一步的功能
        initStart();
    }

    /**
     * 登录信息
     */
    private interface ApiLogData{
        @Headers({"Content-Type:application/json"})
        @POST("/login/registerPatient")
        Call<ResponseBody> logDataPatient(@Body JSONObject jsonObject);

        @Headers({"Content-Type:application/json"})
        @POST("/login/registerFamily")
        Call<ResponseBody> logDataFamily(@Body JSONObject jsonObject);

        @Headers({"Content-Type:application/json"})
        @POST("/login/registerFamilyCheck")
        Call<ResponseBody> logDataFamilyCheck(@Body JSONObject jsonObject);
    }

    private void logDataPatient(String contactPhone){
        RetrofitHelper retrofitHelper=new RetrofitHelper();
        Retrofit retrofit=retrofitHelper.getRetrofit();

        ApiLogData apiLogData=retrofit.create(ApiLogData.class);

        JSONObject jsonObject=new JSONObject();
        Date date=new Date();
        PatientInfomation patientInfomation=new PatientInfomation(uid,"用户"+uid.substring(7),contactPhone,null,
                date,null,null,
//                "https://lztoos.oss-cn-shenzhen.aliyuncs.com/defaultPortrait.jpeg",
                "defaultPortrait.jpeg",    //新用户默认头像
                null);
        String pp=JSON.toJSONString(patientInfomation);
        jsonObject.put("patientInformation",pp);
        Log.d("registerpp", "logDataPatient: "+jsonObject);
        Call<ResponseBody> call=apiLogData.logDataPatient(jsonObject);
        final Response<ResponseBody> response;
        try {
            response=call.execute();
            JSONObject result=JSON.parseObject(response.body().string());
//            Log.d("registerhaha", "logData: "+result);
            if(result.getInteger("code")==1){
                sharedPreferences.edit()
                    .putString("uid",uid)
                    .putString("nickname","用户"+uid.substring(7))
                    .putString("contactPhone",contactPhone)
                    .putString("sex","男")
                        .putString("step","0")

//                    .putString("portrait","https://lztoos.oss-cn-shenzhen.aliyuncs.com/defaultPortrait.jpeg")
                    .putString("portrait","defaultPortrait.jpeg")
                    .putString("identity","patient")
                        .putBoolean("isShow",true)
                    .apply();


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent=new Intent(IndexActivity.this, MainPageActivity.class)
                                .putExtra("isRegister",1);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
            }
            else{
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(IndexActivity.this, result.toString(), Toast.LENGTH_LONG).show();
                    }
                });
            }
//
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void logDataFamilyCheck(String code) {

        RetrofitHelper retrofitHelper = new RetrofitHelper();
        Retrofit retrofit = retrofitHelper.getRetrofit();

        ApiLogData apiLogData = retrofit.create(ApiLogData.class);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        Log.d("indexaccc", "run: ready");
        Call<ResponseBody> call = apiLogData.logDataFamilyCheck(jsonObject);
        final Response<ResponseBody> response;
        try {
            response = call.execute();
            JSONObject result = JSON.parseObject(response.body().string());
            Log.d("indexaccc", "run: "+result.toString());
            if (result.getInteger("code") == 1) {
                //成功
                //患者或家属情况，存入patientinfo和identity
                PatientInfomation patientInfomation=JSON.parseObject(result.getJSONObject("result").getString("patientInfomation"),PatientInfomation.class);

                //存入全局变量 patienInfomation
                sharedPreferences.edit()
                        .putString("uid",patientInfomation.getPatientPhone())
                        .putString("nickname",patientInfomation.getPatientName())
                        .putString("contactPhone",patientInfomation.getPatientContactPhone())
                        .putString("sex",patientInfomation.getPatientSex())
                        .putString("portrait",patientInfomation.getPatientAvatar())
                        .putString("identity","family")
                        .putString("fid",uid)
//                        .putString("pid",contactPhone)
                        .apply();
                Log.d("registerFamily", "logDataFamily: "+sharedPreferences.getString("uid","what"));

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent=new Intent(IndexActivity.this, MainPageActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
            }else if(result.getInteger("code")==4003){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(IndexActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                    }
                });
            }else if(result.getInteger("code")==4002){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(IndexActivity.this, "患者还未收到验证码喔～", Toast.LENGTH_SHORT).show();
                    }
                });
            }else{
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(IndexActivity.this, "未知错误原因", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initStart(){
        btReget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneNumber=etContactPhone.getText().toString().trim();
                if(RegxUtil.isPhone(phoneNumber)){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            getVerifyCode();
                        }
                    }).start();
                }else{
                    Toast.makeText(IndexActivity.this,"请输入手机号",Toast.LENGTH_SHORT).show();
                }

            }
        });
        btStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String contactPhone=etContactPhone.getText().toString().trim();
                if (RegxUtil.isPhone(contactPhone)){
                    //设置紧急联系人
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            hud.show();
                        }
                    });
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if(isPatient==1){
                                //患者注册
                                logDataPatient(contactPhone);
                            }
                            else{
                                Log.d("indexaccc", "run: familylogging");
                                //家属注册
                                String value=etVerifyCode.getText().toString().trim();
                                Log.d("indexaccc", "run: value"+value);
                                if(value.length()!=6){
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(IndexActivity.this,"请输入正确的验证码",Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }else{
                                    logDataFamilyCheck(value);
                                }

                            }

                        }
                    }).start();
                }
                else{
                    //输入了错误格式的手机号码
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(IndexActivity.this,"请输入正确的手机号码",Toast.LENGTH_SHORT).show();
                            etContactPhone.requestFocus();
                        }
                    });
                }
            }
        });
    }

    private void getVerifyCode(){
        String value=etContactPhone.getText().toString().trim();

        RetrofitHelper retrofitHelper = new RetrofitHelper();
        Retrofit retrofit = retrofitHelper.getRetrofit();

        ApiLogData apiLogData = retrofit.create(ApiLogData.class);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("contactPhone", value);
        Call<ResponseBody> call = apiLogData.logDataFamily(jsonObject);
        final Response<ResponseBody> response;
        try{
            response=call.execute();
            if(response.body()!=null){
                JSONObject result=JSON.parseObject(response.body().string());
                Log.d("indexffff", "getVerifyCode: "+result.toString());
                if(result.getInteger("code")==1){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(IndexActivity.this,"验证码已发送至"+value,Toast.LENGTH_SHORT).show();
                            timeCount.start();
                        }
                    });
                }else if(result.getInteger("code")==2003) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(IndexActivity.this, "患者手机号不存在", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(IndexActivity.this,"服务器出错误咯～",Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initChooseIdentity(){
        rlRelative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 加入已选中的样式
                 */
                isPatient=0;
                identify="family";
                //接下来的页面可见
                tvContactTip.setText("*为了能更好的为您提供服务，请在下方填写你的家属的联系方式");
                etContactPhone.setHint("请输入已注册患者的手机号码");
                if (llShowMore.getVisibility()==View.INVISIBLE){
                    llShowMore.setVisibility(View.VISIBLE);
                }
                clVerify.setVisibility(View.VISIBLE);
                if(!getVerifyAlready){
                    btStart.setText("绑定患者");
                }else{
                    btStart.setText("立即体验");
                }
            }
        });
        rlPatient.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 加入已选中的样式
                 */
                isPatient=1;
                identify="patient";
                tvContactTip.setText("*为了能更好的为您提供服务，请在下方填写一个紧急联系人的联系方式");
                etContactPhone.setHint("请输入紧急联系人的手机号码");
                if (llShowMore.getVisibility()==View.INVISIBLE){
                    llShowMore.setVisibility(View.VISIBLE);
                }
                clVerify.setVisibility(View.GONE);
                btStart.setText("立即体验");
            }
        });
    }

    //倒计时类
    class TimeCount extends CountDownTimer {
        private Button bt;
        public TimeCount(long msInFuture, long countDownInterval, Button bt) {
            super(msInFuture,countDownInterval);
            this.bt = bt;
        }

        @Override
        public void onTick(long msUntilFinished) {
            bt.setEnabled(false);
            bt.setText("重新获取("+msUntilFinished/1000 + ")秒");//设置倒计时时间
        }

        @Override
        public void onFinish() {
            bt.setEnabled(true);
            bt.setText("重新获取");
        }
    }
}
